package eztools

import (
	"os"

	"github.com/jhillyerd/enmime"
)

type MailAttachment struct {
	ID, File string
	Content  []byte
}

type MailTo struct {
	Name, Addr string
}

type Mail struct {
	From, Subject, Text, HTML string
	To                        []MailTo
	Inlines, Attachments      []MailAttachment
}

func MailParse(fn string) (ret Mail, err error) {
	r, err := os.OpenFile(fn, os.O_RDONLY, FileCreatePermission)
	if err != nil {
		return
	}
	defer r.Close()

	env, err := enmime.ReadEnvelope(r)
	if err != nil {
		return
	}
	ret.From = env.GetHeader("From")
	alist, _ := env.AddressList("To")
	for _, addr := range alist {
		ret.To = append(ret.To, MailTo{addr.Name, addr.Address})
	}
	ret.Subject = env.GetHeader("Subject")
	ret.Text = env.Text
	ret.HTML = env.HTML
	attachments := func(to []MailAttachment, from []*enmime.Part) {
		for _, in1 := range from {
			to = append(to, MailAttachment{
				in1.ContentID, in1.FileName, in1.Content})
		}
	}
	attachments(ret.Inlines, env.Inlines)
	attachments(ret.Attachments, env.Attachments)
	return
}
